"use strict";
const jwt = require("jsonwebtoken");
const ctl = require("egg").Controller;

class Controller extends ctl {
  success(result) {
    const { ctx } = this;
    ctx.status = 200;
    ctx.body = { code: 200, result };
  }
  fail(message) {
    const { ctx } = this;
    ctx.status = 200;
    ctx.body = { code: -1, message };
  }
  result(code, message, result) {
    const { ctx } = this;
    ctx.status = 200;
    ctx.body = { code, message, result };
  }
  verify() {
    const { ctx, app } = this;
    let token = ctx.request.header.authorization || "";
    if (token.indexOf("Bearer") >= 0) {
      token = token.replace("Bearer ", "");
    }
    let check = false;
    try {
      const result = jwt.verify(token, app.config.jwt.secret);
      if (!result || !result?.uid) {
        this.result(403, "请重新登录");
      } else {
        check = true;
      }
    } catch (err) {
      check = false;
      if (err.name === "TokenExpiredError") {
        // token已过期，返回给客户端的提示
        this.result(403, "请重新登录");
      } else {
        this.result(403, "非法请求");
      }
    }
    return check;
  }
}

module.exports = {
  Controller,
};
